package info.osmatrix.contact.google
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.sampler.getSampleCount;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.utils.ObjectUtil;
	
	import info.osmatrix.contact.events.GDataEvent;

	[Event(name="authSucessEvent", type="info.osmatrix.contact.events.GDataEvent")]  
	[Event(name="groupGetEvent", type="info.osmatrix.contact.events.GDataEvent")]  
	[Event(name="contentGetEvent", type="info.osmatrix.contact.events.GDataEvent")]  
	[Event(name="errorEvent", type="info.osmatrix.contact.events.GDataEvent")]  
	
	public class GDataService extends EventDispatcher
	{
		public static const TYPE_AUTH:String = 'authType';
		public static const TYPE_CONTENT:String = 'contentType';
		public static const TYPE_GROUP:String = 'groupType';
		
		private static const URL_LOGIN:String = 'https://www.google.com/accounts/ClientLogin';
		private static const URL_CONTACTS:String = 'http://www.google.com/m8/feeds/contacts/default/full';
		private static const URL_CONTACTS_BATCH:String = 'http://www.google.com/m8/feeds/contacts/default/full/batch';
		private static const URL_GROUPS:String = 'http://www.google.com/m8/feeds/groups/default/full';
		private static const URL_GROUPS_BATCH:String = 'http://www.google.com/m8/feeds/groups/default/full/batch';
		
		public const NS_ATOM:Namespace = new Namespace('http://www.w3.org/2005/Atom');
		public const NS_GC:Namespace = new Namespace('gContact', 'http://schemas.google.com/contact/2008');
		public const NS_GD:Namespace = new Namespace('gd', 'http://schemas.google.com/g/2005');
		public const NS_BA:Namespace = new Namespace('batch', 'http://schemas.google.com/gdata/batch');
		
		//-----------------------------------------------------------------------------------------------------------------
		private var authURLLoader:URLLoader;		//处理登录相关的提交和返回
		private var contactURLLoader:URLLoader;		//处理通讯录条目相关的提交和返回
		private var groupURLLoader:URLLoader;		//处理组相关的提交和返回
		
		private var token:String;			//保存google登录成功返回的令牌
		private var status:int;			//保存每次提交后返回的HTTP代码
		
		public function GDataService()
		{
			authURLLoader = new URLLoader();
			contactURLLoader = new URLLoader();
			groupURLLoader = new URLLoader();
			
			
			//不可使用HttpStatus事件，如果使用此事件，当返回的http state不为200的时候，载入就不会继续进行，会出现ioerror。
			//使用HTTP_RESPONSE_STATUS事件就可以避免这个问题。
			authURLLoader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, authHttpResponseStatusHandler);
			authURLLoader.addEventListener(Event.COMPLETE, authCmpleteHandler);
			
			contactURLLoader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, contactHttpResponseStatusHandler);
			contactURLLoader.addEventListener(Event.COMPLETE, contactCompleteHandler); 
			
			groupURLLoader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, groupHttpResponseStatusHandler);
			groupURLLoader.addEventListener(Event.COMPLETE, groupCompleteHandler); 
		}
		
		public function login($user:String, $pwd:String):void
		{
			var __request:URLRequest = new URLRequest(URL_LOGIN);
			__request.method = URLRequestMethod.POST;
			
			var __var:URLVariables = new URLVariables();
			__var.accountType = 'GOOGLE';
			__var.Email = $user;
			__var.Passwd = $pwd;
			__var.service = 'cp';
			__var.source = 'zrong-contactImport-1.0';
			__request.data = __var;
			
			authURLLoader.load(__request);
		}
		
		public function getGroups():void
		{
			var __request:URLRequest = new URLRequest(URL_GROUPS);                           
			__request.requestHeaders.push(new URLRequestHeader('Authorization', 'GoogleLogin auth='+token));
			__request.requestHeaders.push(new URLRequestHeader('GData-Version', '3.0'));
			__request.method = URLRequestMethod.GET;
			var __var:URLVariables = new URLVariables();
			//定义一个足够大的值以便于传输所有条目
			__var['max-results'] = 10000;
			__request.data = __var;
			
			groupURLLoader.load(__request);	
		}
		
		public function getContacts():void
		{
			var __request:URLRequest = new URLRequest(URL_CONTACTS);                           
			__request.requestHeaders.push(new URLRequestHeader('Authorization', 'GoogleLogin auth='+token));
			__request.requestHeaders.push(new URLRequestHeader('GData-Version', '3.0'));
			__request.method = URLRequestMethod.GET;
			var __var:URLVariables = new URLVariables();
			//定义一个足够大的值以便于传输所有条目
			__var['max-results'] = 50;
			__request.data = __var;
			
			this.contactURLLoader.load(__request);	
		}
		
		private function authHttpResponseStatusHandler(evt:HTTPStatusEvent):void
		{
			status = evt.status;
//			trace('authHttpResponseStatusHandler', evt);
//			trace('headers:', ObjectUtil.toString(evt.responseHeaders));
//			trace('=================================================='); 
		}
		
		private function authCmpleteHandler(evt:Event):void
		{
			var __arr:Array = String(authURLLoader.data).split('\n');
			//默认事件是直接发送data的值
			var __event:EventVO = new EventVO(TYPE_AUTH, authURLLoader.data);
			if(status == 200)
			{
				var __thirdLine:Array = String(__arr[2]).split('=');
				if(__thirdLine[0] == 'Auth')
				{
					token = __thirdLine[1];
					__event.info = token;
					dispatchEvent(new GDataEvent(GDataEvent.AUTH_SUCCESS_EVENT, __event));
				}
				else
				{
					dispatchEvent(new GDataEvent(GDataEvent.ERROR_EVENT, __event));
				}
						
			}
			else
			{				
				var __firstLine:Array = String(__arr[0]).split('=');
				if(__firstLine[0] == 'Error')
				{
					__event.info = MSG.getError(__firstLine[1]);
					dispatchEvent(new GDataEvent(GDataEvent.ERROR_EVENT, __event));
				}
				else
				{
					dispatchEvent(new GDataEvent(GDataEvent.ERROR_EVENT, __event));
				}
			}
		}
		
		private function groupHttpResponseStatusHandler(evt:HTTPStatusEvent):void
		{
			status = evt.status;
//			trace('groupHttpResponseStatusHandler', evt);
//			trace('headers:', ObjectUtil.toString(evt.responseHeaders));
//			trace('data:', contact.data);
//			trace('=================================================='); 
		}
		

		private function contactHttpResponseStatusHandler(evt:HTTPStatusEvent):void
		{
			status = evt.status;
//			trace('contactHttpResponseStatusHandler', evt);
//			trace('headers:', ObjectUtil.toString(evt.responseHeaders));
//			trace('data:', contact.data);
//			trace('=================================================='); 
		}
		
		private function contactCompleteHandler(evt:Event):void
		{
			var __event:EventVO = new EventVO(TYPE_CONTENT, MSG.getHTTPStatus(status)+'\r'+contactURLLoader.data);
			if(status == 200 || status == 201)
			{
				__event.info = new XML(contactURLLoader.data);
				dispatchEvent(new GDataEvent(GDataEvent.CONTENT_GET_EVENT, __event.info));
			}
			else
			{
				dispatchEvent(new GDataEvent(GDataEvent.ERROR_EVENT, __event));
			}
			//			trace('contactCmpleteHandler', evt);
			//			trace('==================================================');
		}
		
		private function groupCompleteHandler(evt:Event):void
		{
			var __event:EventVO = new EventVO(TYPE_CONTENT, MSG.getHTTPStatus(status)+'\r'+contactURLLoader.data);
			if(status == 200 || status == 201)
			{
				__event.info = new XML(evt.target.data);
				dispatchEvent(new GDataEvent(GDataEvent.GROUP_GET_EVENT, __event.info));
			}
			else
			{
				dispatchEvent(new GDataEvent(GDataEvent.ERROR_EVENT, __event));
			}
			//			trace('contactCmpleteHandler', evt);
			//			trace('==================================================');
		}
	}
}